package com.niit.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.Base64;

public class ByteArrayToBase64Adapter extends TypeAdapter<byte[]> {
    public static final Gson GSON = new GsonBuilder()
            .registerTypeAdapter(byte[].class, new ByteArrayToBase64Adapter())
            .create();

    @Override
    public void write(JsonWriter jsonWriter, byte[] bytes) throws IOException {
        if (bytes == null) {
            jsonWriter.nullValue();
        } else {
            jsonWriter.value(Base64.getEncoder().encodeToString(bytes));
        }
    }

    @Override
    public byte[] read(JsonReader jsonReader) throws IOException {
        String base64 = jsonReader.nextString();
        return Base64.getDecoder().decode(base64);
    }
}
